<template>
  <ly-dialog
    v-model="visible"
    title="记账订单--新增"
    width="1250px"
    fullscreen
    :confirm="handleConfirm"
    :cancel="handleCancel"
    :before-close="() => {$emit('update:visible', false)}"
    @open="handleOpen"
  >
    <template #operation>
      <el-button
        type="primary"
        icon="el-icon-circle-plus-outline"
        @click="handlePush()"
      >增加一行</el-button>
      <el-button
        type="primary"
        icon="el-icon-circle-plus-outline"
        @click="handleCopy()"
      >复制一行</el-button>
      <el-button
        type="primary"
        icon="el-icon-delete"
        class="deleted-button"
        @click="handleBatchDelete()"
      >
        批量删除
      </el-button>
      <el-switch
        v-model="cache"
        style="margin-left: 10px;"
        active-color="#026fff"
        inactive-color="#ff4949"
        active-text="开启缓存"
        inactive-text="关闭缓存"
        @change="handleCache"
      />
    </template>
    <ly-form
      size="mini"
      class="mini-form"
      style="width:100%"
      :model="temp"
      @submit.native.prevent
    >
      <el-row>
        <el-col :span="5">
          <el-form-item
            label="入账日期"
            prop="orderDate"
          >
            <el-date-picker
              v-model="temp.orderDate"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item
            label="平台"
            prop="platform"
          >
            <el-select
              v-model="temp.platform"
              clearable
              placeholder="请选择平台"
              @change="handleChange"
            >
              <el-option
                v-for="item in platformList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item
            label="修改日期"
            prop="modifyTime"
          >
            <el-date-picker
              v-model="temp.modifyTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </ly-form>
    <client-table
      ref="table"
      :style="{ height: `${commonLayoutHeight}px`}"
      :columns="incomeAddColumnDef"
      :data="tableData"
      show-summary
      @selection-change="handleSelectionChange"
      @cell-value-changed="handleCellValueChanged"
    />
  </ly-dialog>
</template>

<script>
import NP from 'number-precision'
import { mapState } from 'vuex'
import { addOne } from '@/api/income'

export default {
  name: 'IncomeAddDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: undefined
    },
    typeList: {
      type: Array,
      default: undefined
    },
    platformList: {
      type: Array,
      default: undefined
    }
  },
  data() {
    return {
      temp: {
        orderDate: '',
        modifyTime: '',
        platform: '',
        platformName: ''
      },
      restTemp: {
        orderDate: '',
        modifyTime: '',
        platform: '',
        platformName: ''
      },
      cache: false,
      tableData: [],
      multipleSelection: [],
      multipleNodeSelection: [],
      incomeAddColumnDef: [
        {
          headerName: '类型',
          field: 'type',
          type: 'selectionColumn',
          headerClass: 'my-class',
          cellEditorParams: {
            list: [],
            props: { label: 'name', value: 'id' },
            select: (node, row) => {
              setTimeout(() => {
                node.data.type = row.id
                node.data.typeName = row.name
                node.setData(node.data)
              }, 300)
            }
          }
        },
        {
          headerName: '收入金额',
          field: 'incomePrice',
          showSummary: true,
          headerClass: 'my-class',
          type: 'numberColumn'
        },
        {
          headerName: '支出金额',
          field: 'expenditurePrice',
          headerClass: 'my-class',
          type: 'numberColumn',
          showSummary: true
        },
        {
          headerName: '差价金额',
          field: 'differencePrice',
          headerClass: 'my-class',
          showSummary: true
        },
        {
          headerName: '备注',
          field: 'remarks',
          singleClickEdit: true,
          type: 'stringColumn'
        }
      ]
    }
  },
  computed: {
    ...mapState('app', {
      commonLayoutHeight: state => state.height.clientHeight - 190
    })
  },
  watch: {
    typeList(val) {
      const tableColumnDef = this.incomeAddColumnDef.find(column => column.field === 'type')
      tableColumnDef.cellEditorParams.list = val
    }
  },
  methods: {
    handleOpen() {
      this.tableData = []
      this.temp = Object.assign({}, this.restTemp)
      setTimeout(() => {
        this.handlePush()
      }, 200)
      // 键盘绑定事件
      const that = this
      document.addEventListener('keydown', that.bindingKeydown)
      // localStorage缓存
      if (localStorage.getItem('cache')) {
        const cache = localStorage.getItem('cache')
        this.cache = cache === 'true'
        if (this.cache === false) return
        if (localStorage.getItem('orderDate')) {
          this.temp.orderDate = localStorage.getItem('orderDate')
        }
        if (localStorage.getItem('platform')) {
          this.temp.platform = localStorage.getItem('platform')
        }
      }
    },
    async handleConfirm() {
      const incomeLists = this.$refs.table.getData()
      const list = this.multipleSelection.filter(item => item.incomePrice === '' || item.expenditurePrice === '' || item.differencePrice === '' || item.type === '' || item.incomePrice === null || item.expenditurePrice === null || item.differencePrice === null || item.type === null)
      if (list.length > 0) {
        return this.$message({
          showClose: true,
          message: '必选项未填！！！',
          type: 'warning',
          center: true
        })
      }
      this.temp.incomeLists = incomeLists
      if (this.cache) {
        window.localStorage.setItem('orderDate', this.temp.orderDate)
        window.localStorage.setItem('platform', this.temp.platform)
      } else {
        window.localStorage.setItem('orderDate', '')
        window.localStorage.setItem('platform', '')
      }
      const result = await addOne('getIncomeAdd', this.temp)
      if (result.code === 200) {
        this.setVisible(false)
        this.$notify({
          title: '成功',
          message: '新增成功',
          type: 'success',
          duration: 2000
        })
        setTimeout(() => {
          this.$emit('add-data')
        }, 300)
      }
    },
    // 下键事件
    bindingKeydown(event) {
      if (event.code === 'ArrowDown') {
        this.handleCopy()
      }
    },
    // 新增
    handlePush() {
      const addRow = this.incomeAddColumnDef.reduce((acc, curr) => {
        acc[curr.field] = ''
        return acc
      }, {})
      const addRows = [addRow]
      addRows[0].incomePrice = 0
      addRows[0].expenditurePrice = 0
      addRows[0].expenditurePrice = 0
      addRows[0].differencePrice = 0
      if (this.multipleSelection.length > 0) {
        const tableData = this.$refs.table.addRowsIndex(this.$refs.table, addRow, this.multipleNodeSelection.rowIndex)
        this.tableData = tableData
      } else {
        this.$refs.table.addRows(addRows)
      }
      this.$refs.table.redrawRows()
      this.$refs.table.selectRow(addRow)
    },
    // 复制
    handleCopy() {
      const addRow = Object.assign({}, this.multipleSelection[0])
      const addRows = [addRow]
      this.$refs.table.addRows(addRows)
      this.$refs.table.redrawRows()
      this.$refs.table.selectRow(addRow)
      this.$refs.table.syncSummaryRow(this.$refs.table.getData())
    },
    // 删除
    handleBatchDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          showClose: true,
          message: '请勾选要删除项',
          type: 'warning',
          center: true
        })
        return
      }
      this.$refs.table.removeRows(this.multipleSelection)
      this.$refs.table.syncSummaryRow(this.$refs.table.getData())
    },
    // 缓存
    handleCache(val) {
      window.localStorage.setItem('cache', val)
    },
    // 双击修改
    handleCellValueChanged(e) {
      // 计算规则
      // 差价金额 = 收入金额 — 支出金额
      if (e.value !== e.oldValue) {
        e.data.differencePrice = NP.round(NP.minus(Number(e.data.incomePrice), Number(e.data.expenditurePrice)), 2)
        this.$refs.table.redrawRows()
      }
      this.$refs.table.syncSummaryRow(this.$refs.table.getData())
    },
    handleSelectionChange(val, node) {
      this.multipleSelection = val
      this.multipleNodeSelection = node[0]
    },
    handleChange(val) {
      const list = this.platformList.filter(item => item.id === val)
      if (list.length > 0) {
        this.temp.platformName = list[0].name
      }
    },
    handleCancel() {
      this.setVisible(false)
    },
    setVisible(flag) {
      this.$emit('update:visible', flag)
    }
  }
}
</script>

<style>
</style>
